package controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import com.sun.org.apache.xerces.internal.impl.xpath.regex.REUtil;
import com.sun.org.apache.xpath.internal.operations.Mod;
import dao.IGoodsDao;
import model.Goods;

import org.apache.commons.io.IOUtils;
import org.apache.ibatis.logging.stdout.StdOutImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import service.IGoodsService;
import service.impl.GoodsService;
import util.DateUtil;

import javax.jws.WebParam;
import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/goods")
public class GoodsController {
    @Autowired
    private IGoodsService iGoodsService;


    @RequestMapping("/list")//查询上架商品
    public ModelAndView list(Goods goods){
        int totalCount = iGoodsService.totalCount(goods);
        System.out.println("总行数："+totalCount);
        int totalPage;
        if (totalCount % goods.getRowCount() == 0) {
            totalPage = (int) totalCount / goods.getRowCount();

        } else {
            totalPage = (int) totalCount / goods.getRowCount() + 1;
        }
        ModelAndView mv = new ModelAndView();
        if((goods.getgName()!=null && goods.getgName()!="") ){
            if(iGoodsService.list(goods).size()!=0){
                mv.addObject("obj", iGoodsService.list(goods).get(0));
            }else{
                totalPage += 1;
            }

        }
        if(goods.getParentId()!=null){
            if(iGoodsService.list(goods).size()!=0){
                mv.addObject("pid",iGoodsService.list(goods).get(0));
            }else{
                totalPage += 1;
            }
        }
        if(goods.getsId()!=null){
            if(iGoodsService.list(goods).size()!=0){
                mv.addObject("sid",iGoodsService.list(goods).get(0));
            }
        }
        System.out.println("商品名"+goods.getgName()+", 一级分类："+goods.getSortId());


        List<Goods> list = iGoodsService.list(goods);
        list.forEach(l -> System.out.println(l.getImgUrl()));
        List<Goods> parent = iGoodsService.selectParentId(goods);
        List<Goods> sort = iGoodsService.sort(goods);

        System.out.println(parent);
        mv.addObject("parent", parent);
        mv.addObject("sort", sort);
        mv.addObject("list",list);
        mv.addObject("totalPage", totalPage);
        mv.addObject("pageNo", goods.getPageNo());
        mv.setViewName("manager/commodity_list");
        return  mv;
    }

    @RequestMapping(value = "sId",produces = "text/html;charset=utf-8")
    @ResponseBody
    public String sortId(Goods goods){
        return  iGoodsService.selectSortId(goods);
    }

    @RequestMapping("updatePage")//弹出更新页面
    public ModelAndView updatePage(Goods goods){
        ModelAndView mv= new ModelAndView();
        List<Goods> list = iGoodsService.list(goods);
        List<Goods> sort = iGoodsService.sort(goods);
        if (list.size() != 0) {
            mv.addObject("obj", list.get(0));
        }
        mv.addObject("sort", sort);
        mv.setViewName("manager/commodity_update");
        return  mv;
    }

    @RequestMapping(value = "update", produces = "text/html;charset=utf-8")//更新商品列表的商品信息
    @ResponseBody
    public String update (Goods goods){
        goods.setImgUrl(goods.getImgUrl().replace("E:/images/",""));
        int count = iGoodsService.update(goods);
        if(count > 0 ){
            return  "1";
        }else{
            return  "0";
        }
    }

    @RequestMapping("insertPage")//跳转新增商品页面
    public ModelAndView insertPage(Goods goods){
        ModelAndView mv = new ModelAndView();
        List<Goods> sort = iGoodsService.sort(goods);

        mv.addObject("sort", sort);

        mv.setViewName("manager/commodity_add");
        return  mv;
    }

    @RequestMapping("insert")//新增商品
    @ResponseBody
    public String insert(Goods goods){
        goods.setImgUrl(goods.getImgUrl().replace("E:/images/",""));
        int count = iGoodsService.insert(goods);
        System.out.println("count的值:"+count);
        if(count >0){
            return  "1";
        }else{
            return  "0";
        }
    }

    //上传图片
    @RequestMapping("/upload")
    @ResponseBody
    public String uploadFile(@RequestParam("file") MultipartFile imgFile) throws IOException {
        //@RequestParam用于将指定名称的请求参数赋值给方法中的形参
        String contentType = imgFile.getContentType();//IMAGE/PNG
        System.out.println(contentType);

        String name = imgFile.getName();
        System.out.println(name);

        String originalName = imgFile.getOriginalFilename();
        System.out.println(originalName);

        long size = imgFile.getSize();
        System.out.println(size);

        InputStream in = null;
        OutputStream out = null;
        //文件目的地址
        String filePath = "D:/img/goods/";
        File file = new File(filePath);
        if(!file.exists()){
            file.mkdir();
        }
        try{
            //根据源文件获取输入流
            in = imgFile.getInputStream();
            //生成目标文件名
            filePath += DateUtil.dateFormat()+".jpg";
            //创建文件输出流
            out = new FileOutputStream(new File(filePath));
            //读取输入流，将读取的字节写入到数据流并刷新输出流
            IOUtils.copy(in, out);
        } catch (IOException e){
            e.printStackTrace();
        } finally {
            if (in != null){
                in.close();
            }
            if (out != null){
                out.close();
            }
        }

        System.out.println(filePath);
        JSONObject json = new JSONObject();
        json.put("code", 1);
        json.put("imgUrl", filePath);
        return json.toJSONString();
    }

    @RequestMapping("listOff")//查询下架商品
    public ModelAndView queryOff(Goods goods){

        int totalCount = iGoodsService.totalCountOff(goods);
        System.out.println("总行数："+totalCount);
        int totalPage;
        if (totalCount % goods.getRowCount() == 0) {
            totalPage = (int) totalCount / goods.getRowCount();

        } else {
            totalPage = (int) totalCount / goods.getRowCount() + 1;
        }
        ModelAndView mv = new ModelAndView();
        if((goods.getgName()!=null && goods.getgName()!="") ){
            if(iGoodsService.queryOff(goods).size()!=0){
                mv.addObject("obj", iGoodsService.queryOff(goods).get(0));
            }else{
                totalPage += 1;
            }

        }
        if(goods.getParentId()!=null){
            if(iGoodsService.queryOff(goods).size()!=0){
                mv.addObject("pid",iGoodsService.queryOff(goods).get(0));
            }else{
                totalPage += 1;
            }
        }
        if(goods.getsId()!=null){
            if(iGoodsService.queryOff(goods).size()!=0){
                mv.addObject("sid",iGoodsService.queryOff(goods).get(0));
            }
        }
        List<Goods> list = iGoodsService.queryOff(goods);
        List<Goods> parent = iGoodsService.selectParentId(goods);
        List<Goods> sort = iGoodsService.sort(goods);
        mv.addObject("list", list);
        mv.addObject("parent" ,parent);
        mv.addObject("sort", sort);
        mv.addObject("pageNo", goods.getPageNo());
        mv.addObject("totalPage", totalPage);
        mv.setViewName("manager/offcommodity_list");
        return  mv;
    }

    @RequestMapping("down")//一键下架商品
    public ModelAndView down(String ids){
        if(ids !=null && ids.length()!=0){
            Map<String,String> map = new HashMap<>();
            map.put("gStatus", "0");
            map.put("ids",ids );
            iGoodsService.updateStatus(map);
        }

        return list(new Goods());
    }
    @RequestMapping("up")
    public ModelAndView up(String ids){
        if(ids!=null && ids.length()!=0){
            Map<String,String> map = new HashMap<>();
            map.put("gStatus", "1");
            map.put("ids",ids );
            iGoodsService.updateStatus(map);
        }
        return  queryOff(new Goods());
    }

}
